package com.apps.ftapp.fragment;


import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.afollestad.materialdialogs.MaterialDialog;
import com.apps.ftapp.R;
import com.apps.ftapp.activity.BookDetailActivity;
import com.apps.ftapp.activity.LessonDetailActivity;
import com.apps.ftapp.activity.SubjectMoreActivity;
import com.apps.ftapp.activity.ZhenTiNewActivity;
import com.apps.ftapp.adapter.IndexAdapter;
import com.apps.ftapp.bean.BookBean;
import com.apps.ftapp.bean.CategoriesBean;
import com.apps.ftapp.bean.NewIndex;
import com.apps.ftapp.bean.TestpapersBean;
import com.apps.ftapp.loader.GlideImageLoader;
import com.apps.ftapp.model.BaseItem;
import com.apps.ftapp.model.IndexModel1;
import com.apps.ftapp.model.IndexTitle;
import com.apps.ftapp.model.LessonModel;
import com.apps.ftapp.ui.ExamActivity;
import com.apps.ftapp.util.ActivitySkipUtil;
import com.apps.ftapp.util.Async;
import com.apps.ftapp.util.BroadCastManager;
import com.apps.ftapp.util.Constant;
import com.apps.ftapp.util.L;
import com.apps.ftapp.util.SharedPreferencesUtil;
import com.apps.ftapp.util.Tools;
import com.dou361.dialogui.DialogUIUtils;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cz.msebera.android.httpclient.Header;

/**
 * A simple {@link Fragment} subclass.
 * 首页 fragment
 */
public class HomeFragment extends Fragment implements IndexAdapter.MyClickListener {


    @BindView(R.id.listView)
    ListView listView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    Unbinder unbinder;
    private ImageLoader imageLoader = ImageLoader.getInstance();

    private MaterialDialog dialog;
    private DisplayImageOptions options;
    //轮播图
    private Gson gson = new Gson();
    private LocalReceiver mReceiver;

    private TextView topTit;

    private String yiji_name;

    //分类
    private List<CategoriesBean> fenleiList = new ArrayList<>();

    //真韪同
    private List<TestpapersBean> zhentiList = new ArrayList<>();

    //图书
    private List<BookBean> bookList = new ArrayList<>();

    //真题
    List<LessonModel.DataBean> lessonlist = new ArrayList<>();


    private IndexModel1 indexModel1 = new IndexModel1();

    //
    private String[] TAB_TITLES = {"题库练习", "", "教师资格证", "", "推荐图书", "真题/模考"};
    private String[] TAB_MORE = {"", "", "更多", "", "更多", "更多"};

    private Banner banner;
    String tempData = new String();


    private IndexAdapter indexAdapter;

    private List<BaseItem> dataList = new ArrayList<>();
    private NewIndex newIndex;//首页全部收据汇总

    CallBack call;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        call = (CallBack) getActivity();
    }

    public HomeFragment() {
        // Required empty public constructor
        //显示图片的配置  

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //接收广播
        try {
            IntentFilter filter = new IntentFilter();
            filter.addAction("fragment_home_left");
            mReceiver = new LocalReceiver();
            BroadCastManager.getInstance().registerReceiver(getActivity(),
                    mReceiver, filter);//注册广播接收者
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_index, container, false);
        unbinder = ButterKnife.bind(this, view);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        dorefresh();
                    }
                }, 1500);
            }
        });
        init();

        return view;
    }


    private void init() {
        dataList.clear();
        refreshLayout.setEnableLoadMore(false);
        for (int j = 0; j < 6; j++) {
            dataList.add(new IndexTitle(0, TAB_TITLES[j], TAB_MORE[j]));
            switch (j) {
                case 0:
                    //题库练习
                    dataList.add(new IndexTitle(1, "题库练习", ""));
                    break;
                case 1:
                    //学习计划
                    dataList.add(new IndexTitle(2, "学习计划", ""));
                    break;
                case 2:
                    //教师资格证
                    dataList.add(new IndexTitle(3, "教师资格证", ""));
                    break;
//                case 3:
//                    //教师招聘
//                    dataList.add(new IndexTitle(4,"教师招聘",""));
//                    break;
                case 4:
                    //图书
                    dataList.add(new IndexTitle(5, "图书", ""));
                    //    dataList.add(new IndexTitle(5,"图书",""));
                    break;
                case 5:
                    //图书
//                    dataList.add(new IndexTitle(6,"图书",""));
//                    dataList.add(new IndexTitle(6,"图书",""));
                    break;
            }

        }


        //设置图片加载器
        View view = LayoutInflater.from(getContext()).inflate(R.layout.fragment_index_banner, null);

        topTit = view.findViewById(R.id.index_btn);
        //设置图片加载器
        banner = view.findViewById(R.id.banner);
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        banner.setImageLoader(new GlideImageLoader());
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(3500);
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.Default);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {

            }
        });
        yiji_name = SharedPreferencesUtil.getData(getContext(), "yijiName", "") + "";
        L.i("main", "yiji_name>>>>" + yiji_name);
        if (!"".equals(Tools.isNull(yiji_name))) {
            topTit.setText(Tools.isNull(yiji_name));
        } else {
            topTit.setText("自学考试");
        }
        if (null != dialog) {
            dialog.dismiss();
        }

        topTit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                tanchuang();
            }


        });

        indexAdapter = new IndexAdapter(getContext(), dataList, indexModel1, fenleiList, bookList, this, yiji_name);
        listView.addHeaderView(view);
        listView.setAdapter(indexAdapter);
        loaddata(0);
        getlesson();
    }

    //加载首页数据  0初始载入 1刷新
    private void loaddata(final int type) {
        RequestParams params = new RequestParams();
        params.put("token", Constant.token);
        params.put("userId", Constant.uid);
        Async.post("tiku/home", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    L.i("main", "<<<111111<<<<" + new String(responseBody) + "......");
                    try {
                        newIndex = gson.fromJson(new String(responseBody), NewIndex.class);
                        if (1 == Tools.isIntNull(newIndex.getSuccess())) {
                            final NewIndex.TanchuangBean tanchuangBean = newIndex.getTanchuang();
                            if (null != tanchuangBean && Tools.isNull(tanchuangBean.getIst()).equals("1")) {
                                View view = View.inflate(getActivity(), R.layout.view_location_dialog_dong, null);
                                ImageView imageView = view.findViewById(R.id.start_img);
                                imageLoader.displayImage(tanchuangBean.getImgurl(), imageView, options);
                                if (type > 0) {
                                    try {
                                        final Dialog dialog = DialogUIUtils.showCustomAlert(getActivity(), view).show();
                                        imageView.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                if (null != dialog)
                                                    dialog.dismiss();// 关闭弹出框
                                                if ("testpaper".equals(tanchuangBean.getType())) {
                                                    //字段 type为类型 当为“testpaper”的时候是模考广告，根据字段id 进入此模考页面
                                                    HashMap map = new HashMap();
                                                    map.put("id", tanchuangBean.getId());
                                                    ActivitySkipUtil.skipAnotherForActivity(getActivity(), ExamActivity.class, map);
                                                } else if ("course".equals(tanchuangBean.getType())) {
                                                    //当字段type为“course”的时候，是课程广告 ，根据字段id 进入此课程详情页
                                                    HashMap<String, Object> map = new HashMap();
                                                    map.put("id", tanchuangBean.getId());
                                                    map.put("title", "课程详情");
                                                    ActivitySkipUtil.skipAnotherActivity(getActivity(), LessonDetailActivity.class, map);
                                                } else if ("book".equals(tanchuangBean.getType())) {
                                                    //当字段type为“book”的时候，是图书广告 ，根据字段id 进入此图书详情页
                                                    HashMap<String, Object> params = new HashMap<>();
                                                    params.put("id", tanchuangBean.getId());
                                                    ActivitySkipUtil.skipAnotherActivity(getActivity(), BookDetailActivity.class, params);
                                                }
                                            }
                                        });
                                        Button mClose_btn = view.findViewById(R.id.btn_close);
                                        mClose_btn.setOnClickListener(new View.OnClickListener() {

                                            @Override
                                            public void onClick(View v) {
                                                dialog.dismiss();// 关闭弹出框
                                            }
                                        });
                                    } catch (Exception e) {
                                        e.printStackTrace();

                                    }
                                }
                            }
                            //成功之后的操作逻辑
                            initbanner();
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    //加载数据
                    //loadZhenti();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });


    }

    //头部banner
    private void initbanner() {
        List<String> imgList = new ArrayList<>();
        for (String str : newIndex.getBanners()) {
            imgList.add(str);
        }
        banner.setImages(imgList);
        banner.start();
        initzp();
    }


    //招聘及资格证相关
    private void initzp() {
        IndexModel1 indexModel1 = new IndexModel1();
        if (yiji_name.equals("教师资格证")) {
            indexModel1.setZigezheng(newIndex.getZigezheng());
        } else {
            indexModel1.setZhaopin(newIndex.getZhaopin());
        }
        indexAdapter.addRes(indexModel1);
        initbook();
    }

    //加载图书
    private void initbook() {
        bookList.addAll(newIndex.getData());
        initfenlei();
    }

    //加载分类
    private void initfenlei() {
        fenleiList.addAll(newIndex.getCategories());
        indexAdapter.notifyDataSetChanged();
        inittest();
    }

    private void inittest() {
        for (TestpapersBean testpapersBean : newIndex.getTestpapers()) {
            zhentiList.add(testpapersBean);
        }
        if (null != dataList && dataList.size() > 0) {
            for (int i = 0; i < dataList.size(); i++) {
                IndexTitle indexTitle = (IndexTitle) dataList.get(i);
                if (indexTitle.getItem_type() == 6) {
                    dataList.remove(i);
                }
            }
        }
        for (TestpapersBean z : newIndex.getTestpapers()) {
            dataList.add(new IndexTitle(6, z.getName(), z.getId(), Tools.isNull(z.getAlready())));
        }

        zhentiList.addAll(newIndex.getTestpapers());


    }


    private void dorefresh() {
        yiji_name = SharedPreferencesUtil.getData(getContext(), "yijiName", "") + "";
        L.i("main", "yiji_--------------name>>>>" + yiji_name);
        if (!"".equals(Tools.isNull(yiji_name))) {
            topTit.setText(Tools.isNull(yiji_name));
        } else {
            topTit.setText("自学考试");
        }

        fenleiList.clear();
        zhentiList.clear();

        //
        if (null != dataList && dataList.size() > 0) {

            for (int i = 0; i < dataList.size(); i++) {
                IndexTitle indexTitle = (IndexTitle) dataList.get(i);
                if (indexTitle.getItem_type() == 6) {
                    L.i("main", "mmbw ,,,,,");
                    dataList.remove(indexTitle);
                }
            }
        }
        loaddata(0);
        indexAdapter = new IndexAdapter(getContext(), dataList, indexModel1, fenleiList, bookList, this, yiji_name);
        listView.setAdapter(indexAdapter);
        indexAdapter.notifyDataSetChanged();
        refreshLayout.finishRefresh();
    }

    private void tanchuang() {
        if (null != dialog) {
            dialog.dismiss();
        }
        dialog = new MaterialDialog.Builder(getActivity())
                .customView(R.layout.fragment_index_top, false)
                .show();


        View customeView = dialog.getCustomView();
        TextView quxiao = customeView.findViewById(R.id.quxiao);
        TextView queding = customeView.findViewById(R.id.queding);

        //
        TextView kaoshiVal = customeView.findViewById(R.id.kaoshi_val);
        TextView xueduanVal = customeView.findViewById(R.id.xueduan_val);
        TextView xuekeVal = customeView.findViewById(R.id.xueke_val);


        String yiji_name = SharedPreferencesUtil.getData(getContext(), "yijiName", "") + "";
        String erji_name = SharedPreferencesUtil.getData(getContext(), "erjiName", "") + "";
        String sanji_name = SharedPreferencesUtil.getData(getContext(), "sanjiName", "") + "";
        if (!"".equals(Tools.isNull(yiji_name))) {
            kaoshiVal.setText(Tools.isNull(yiji_name));
        } else {
            kaoshiVal.setText("自学考试");
        }
        if (!"".equals(Tools.isNull(erji_name))) {
            xueduanVal.setText(Tools.isNull(erji_name));
        } else {
            xueduanVal.setText(Tools.isNull("学前"));
        }
        if (!"".equals(Tools.isNull(sanji_name))) {
            xuekeVal.setText(Tools.isNull(sanji_name));
        } else {
            xuekeVal.setText(Tools.isNull("数学"));
        }

        quxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.hide();
            }
        });

        queding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != dialog) {
                    dialog.dismiss();
                }

                Constant.IS_EDIT_CHANAGE = "IndexFragment";

                ActivitySkipUtil.skipAnotherActivity(getActivity(), SubjectMoreActivity.class, false);
            }
        });

    }


    class LocalReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            //收到广播后的处理
            dorefresh();

        }

    }


    public interface CallBack {
        void getData(String str);
    }


    @Override
    public void clickListener(View v) {
        String tag1 = (String) v.getTag();

        L.i("main", "-------------------------------" + tag1);
        if ("教师资格证".equals(Tools.isNull(tag1))) {
            call.getData(tag1);
        } else if ("推荐图书".equals(Tools.isNull(tag1))) {
            call.getData(tag1);
        } else {
            //跳转到
            ActivitySkipUtil.skipAnotherActivity(getActivity(), ZhenTiNewActivity.class, false);
        }

        int tag = Tools.isIntNull(tag1);

        switch (tag) {
            case 1:

                //题库练习
                break;


            case 2:
                //学习计划
                break;


            case 3:
                //教师资格证
                call.getData("教师资格证");
                break;


            case 4:

                //教师招聘
                break;


            case 5:

                //图书
                break;
        }
    }

    private void getlesson() {
        RequestParams params = new RequestParams();
        params.put("categoryId", 1);
        params.put("zxueke", "");
        params.put("xueke", "");
        params.put("xueduan", "");
        params.put("leibie", "");
        params.put("page", 1);
        Async.get("course/explore", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {

                if (statusCode == 200) {
                    L.i("main", ":::::" + new String(responseBody));
                    LessonModel result = gson.fromJson(new String(responseBody), LessonModel.class);
                    if (null != result.getData()) {
                        lessonlist = result.getData();
//                        if (curPage == 1) {
//                            lessonAdapter.clear();
//                            lessonAdapter.notifyDataSetChanged();
//                        } else {
//
//                        }
//                        lessonAdapter.addAll(result.getData());
                    }

                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });


    }


}
